package com.globant.fragment;

import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.globant.common.BusinessSettings;
import com.globant.common.MyPositionOverlay;
import com.globant.dao.PlaceDao;
import com.globant.domain.PlaceBean;
import com.globant.placemaps.MainActivity;
import com.globant.placemaps.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class MapFragment extends Fragment {
	
	EditText name;
	EditText description;
	Button add;
	MapView mapa;
	MyPositionOverlay om;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
	
	@Override 
	public View onCreateView(LayoutInflater inflater, ViewGroup container,  
		Bundle savedInstanceState) {  
		
		super.onCreate(savedInstanceState);
		
		View layout = inflater.inflate(R.layout.maps, container, false);
		mapa = (MapView) layout.findViewById(R.id.mapa);
		mapa.setBuiltInZoomControls(true);
		
		List<Overlay> capas = mapa.getOverlays();
		om = new MyPositionOverlay();
		capas.add(om);
		mapa.postInvalidate();
		
		name = (EditText) layout.findViewById(R.id.name);
		description = (EditText) layout.findViewById(R.id.description);
		add = (Button) layout.findViewById(R.id.add);
		
		add.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				addNewElement();
			}
		});
		
		return layout;  
	}  
	
	private void addNewElement() {
		if (name.getText().length() == 0 || description.getText().length() == 0 || om.getGeoPoint() == null) {
			MainActivity activity = (MainActivity) getActivity();
			activity.showDialog(BusinessSettings.ERROR_DIALOG);
		} else {
			PlaceDao placeDao = new PlaceDao(getActivity().getApplication());
			PlaceBean place = new PlaceBean(name.getText().toString(),
					description.getText().toString(), om.getGeoPoint()
							.getLatitudeE6(), om.getGeoPoint().getLongitudeE6());
			placeDao.insert(place);
			
			PlacesFragment map = (PlacesFragment)getFragmentManager().findFragmentById(R.id.titles);
			map.obtainList();
			
			name.setText("");
			description.setText("");
		}
	}


	public void modifyLocation(int latitude, int longitude) {
        MapController controlMapa = mapa.getController();
        GeoPoint geoPoint = new GeoPoint(latitude, longitude);
        controlMapa.setCenter(geoPoint);
        controlMapa.setZoom(10);
        
		List<Overlay> capas = mapa.getOverlays();
		MyPositionOverlay om = new MyPositionOverlay(geoPoint);
		capas.add(om);
		mapa.postInvalidate();
		
	}
    
}
